package com.newland.esp.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @param
 * @author lw
 * @descripe
 * @date 2021/8/16 9:25
 * @Version 1.0
 **/
@Slf4j
public class ThreadLocalUtils {
    private ThreadLocalUtils() {

    }

    private static ThreadLocal<HttpServletRequest> request = new ThreadLocal<>();

    private static ThreadLocal<String> string = new ThreadLocal<>();

    private static ThreadLocal<HashMap> map = ThreadLocal.withInitial(() -> new HashMap(16));


    public static void setRequest(HttpServletRequest httpServletRequest){
        request.set(httpServletRequest);
    }

    public static HttpServletRequest getRequest(){
        return request.get();
    }

    public static void setString(String str) {
        string.set(str);
    }

    public static String getString() {
        return string.get();
    }

    public static void setMap(String key, Object value) {
        map.get().put(key, value);
    }

    public static Object getMap(String key) {
        return map.get().get(key);
    }

    public static HashMap getMapAll() {
        return map.get();
    }

    /**
     * tomcat的线程池大小是有限的，如果请求数大于tomcat线程池大小，就会出现同一个线程处理不同的请求，那么后面的请求就可能看到前面的请求往ThreadLocal放的脏数据。
     * 因此，每次请求（http或者websocket）处理完毕，需要清理ThreadLocal
     */
    public static void clear() {
        // 注意：谨慎使用api，仅清理当前线程即可
        request.set(null);
        string.set(null);
        map.get().clear();
        log.info("ThreadLocal clear successfully");
    }
}
